<template>
  <n-grid :cols="12">
    <n-grid-item :offset="2" span="8">
      <detail-page-header title="添加产品">
        <div>
          <n-button class="mr-2">重置</n-button>
          <n-button type="primary" @click.stop="handleSubmit">保存</n-button>
        </div>
      </detail-page-header>
      <div class="mt-[16px]">
        <n-card>
          <n-form ref="formRef" :model="modelForm" :rules="rules">
            <n-row :gutter="10">
              <n-col :span="24">
                <n-form-item label="产品名称" path="name">
                  <n-input
                    v-model:value="modelForm.name"
                    placeholder="请输入产品名称"
                  />
                </n-form-item>
              </n-col>
              <n-col :span="12">
                <n-form-item label="产品分类" path="categoryId">
                  <n-select
                    v-model:value="modelForm.categoryId"
                    value-field="id"
                    label-field="name"
                    clearable
                    :options="categories"
                    placeholder="请选择产品分类"
                  />
                </n-form-item>
              </n-col>
              <n-col :span="12">
                <n-form-item label="品牌" path="brandId">
                  <n-select
                    v-model:value="modelForm.brandId"
                    value-field="id"
                    label-field="name"
                    clearable
                    :options="brands"
                    placeholder="请选择品牌"
                  />
                </n-form-item>
              </n-col>
              <n-col :span="12">
                <n-form-item label="产品封面">
                  <n-upload
                    response-type="json"
                    :headers="headers"
                    :action="`${uploadUrl}?biz=product-avatar`"
                    v-model:file-list="coverFileList"
                    :max="1"
                    list-type="image-card"
                    @finish="handleUploadFinishCover"
                    @remove="handleUploadRemoveCover"
                  >
                    点击上传
                  </n-upload>
                </n-form-item>
              </n-col>
              <n-col :span="12">
                <n-form-item label="产品图片">
                  <n-upload
                    response-type="json"
                    :headers="headers"
                    :action="`${uploadUrl}?biz=product-gallery`"
                    v-model:file-list="galleryFileList"
                    :max="5"
                    list-type="image-card"
                    @finish="handleUploadFinishGallery"
                    @remove="handleUploadRemoveGallery"
                  >
                    点击上传
                  </n-upload>
                </n-form-item>
              </n-col>
              <n-col :span="24">
                <n-form-item label="附加属性">
                  <n-space>
                    <n-checkbox
                      :checked-value="'1'"
                      :unchecked-value="'0'"
                      v-model:checked="modelForm.canTradein"
                    >
                      可回收
                    </n-checkbox>
                    <n-checkbox
                      :checked-value="'1'"
                      :unchecked-value="'0'"
                      :disabled="modelForm.canTradein === '1'"
                      v-model:checked="modelForm.hasVariant"
                    >
                      多SKU
                    </n-checkbox>
                    <n-checkbox
                      :checked-value="'1'"
                      :unchecked-value="'0'"
                      v-model:checked="modelForm.canRepairable"
                    >
                      可维修
                    </n-checkbox>
                    <n-checkbox
                      :checked-value="'1'"
                      :unchecked-value="'0'"
                      v-model:checked="modelForm.hasSerialNumber"
                    >
                      有序列号
                    </n-checkbox>
                  </n-space>
                </n-form-item>
              </n-col>
              <template v-if="modelForm.hasVariant === '1'">
                <n-col :span="24">
                  <n-divider title-placement="left"> SKU属性 </n-divider>
                </n-col>
                <template
                  v-for="attrItem in modelForm.attributes"
                  :key="attrItem.uuid"
                >
                  <n-col :span="5">
                    <n-form-item :show-label="false">
                      <n-select
                        v-model:value="attrItem.attributeId"
                        value-field="id"
                        label-field="name"
                        clearable
                        :options="attributeSelectOpts"
                        placeholder="请选择属性"
                        @clear="() => handleClearAttributeId(attrItem)"
                        :rule:="{
                          required: true,
                          message: `请选择属性`,
                          trigger: ['change', 'blur'],
                        }"
                      ></n-select>
                    </n-form-item>
                  </n-col>
                  <n-col :span="showRemoveAttrBtn ? 18 : 19">
                    <n-form-item :show-label="false">
                      <n-select
                        multiple
                        value-field="id"
                        label-field="name"
                        placeholder="请选择属性值"
                        clearable
                        :options="getAttributeValues(attrItem.attributeId)"
                        @update:value="
                          (_:any, selectOption: SelectOption) =>
                            handleUpdateAttributeValue(attrItem, selectOption)
                        "
                        v-model:value="attrItem.attributeValueIds"
                        :rule:="{
                          required: true,
                          message: `请选择属性值`,
                          trigger: ['change', 'blur'],
                        }"
                      ></n-select>
                    </n-form-item>
                  </n-col>
                  <n-col :span="1" v-if="showRemoveAttrBtn">
                    <n-form-item :show-label="false">
                      <n-button
                        block
                        strong
                        quaternary
                        text
                        type="error"
                        @click.stop="handleRemoveAttribute(attrItem.uuid)"
                      >
                        <n-icon size="30">
                          <CloseCircle />
                        </n-icon>
                      </n-button>
                    </n-form-item>
                  </n-col>
                </template>
                <n-col :span="24" class="text-right" v-if="showAddAttrBtn">
                  <n-button
                    quaternary
                    type="primary"
                    @click.stop="handleAddAttribute"
                  >
                    <template #icon>
                      <AddCircle />
                    </template>

                    添加属性
                  </n-button>
                </n-col>
              </template>
              <template v-if="modelForm.hasVariant !== '1'">
                <n-col :span="24">
                  <n-divider title-placement="left"> 价格配置 </n-divider>
                </n-col>
                <n-col :span="12">
                  <n-form-item label="原价" path="originalPrice">
                    <n-input-number
                      class="w-full"
                      clearable
                      placeholder="请输入原价"
                      v-model:value="modelForm.originalPrice"
                    />
                  </n-form-item>
                </n-col>
                <n-col :span="12">
                  <n-form-item label="成交价" path="currentPrice">
                    <n-input-number
                      class="w-full"
                      clearable
                      placeholder="请输入成交价"
                      v-model:value="modelForm.currentPrice"
                    />
                  </n-form-item>
                </n-col>
              </template>
              <n-col :span="24">
                <n-divider title-placement="left"> 可选配置 </n-divider>
              </n-col>
              <template v-if="modelForm.hasVariant !== '1'">
                <n-col :span="12">
                  <n-form-item label="SKU" path="sku">
                    <n-input
                      clearable
                      placeholder="请输入SKU"
                      v-model:value="modelForm.sku"
                    />
                  </n-form-item>
                </n-col>
                <n-col :span="12">
                  <n-form-item label="重量" path="weight">
                    <n-input-number
                      class="w-full"
                      clearable
                      placeholder="请输入重量"
                      v-model:value="modelForm.weight"
                    />
                  </n-form-item>
                </n-col>
              </template>
              <n-col :span="24">
                <n-form-item label="排序" path="sort">
                  <n-input-number
                    class="w-full"
                    clearable
                    placeholder="请输入排序"
                    v-model:value="modelForm.sort"
                  />
                </n-form-item>
              </n-col>
              <n-col :span="24">
                <n-form-item label="描述" path="description">
                  <n-input
                    placeholder="请输入描述"
                    type="textarea"
                    v-model:value="modelForm.description"
                  />
                </n-form-item>
              </n-col>
            </n-row>
          </n-form>
        </n-card>
      </div>
    </n-grid-item>
  </n-grid>
</template>
<script setup lang="ts">
import { v4 as uuidv4 } from "uuid";
import { FormInst, SelectOption, UploadFileInfo, useMessage } from "naive-ui";
import { onMounted, ref, reactive, watch, computed } from "vue";
import { CloseCircle, AddCircle } from "@vicons/ionicons5";
import { cloneDeep, get } from "lodash-es";
import { getCategories } from "@/api/product/category.api";
import { getBrands } from "@/api/product/brand.api";
import { createProduct, } from "@/api/product/product.api";
import { getAllAttributes } from "@/api/product/productAttribute.api";
import { Category } from "@/types/model/product/vos/category.vo";
import { getHeaders } from "@/common/utils/comps/index";
import { uploadUrl } from "@/api/basic/basic.api";
import { rules } from "./data";

const headers = getHeaders();
const message = useMessage();

const formRef = ref<FormInst | null>(null);
const categories = ref<Category[]>([]);
const brands = ref<any>([]);
const attributes = ref<any[]>([]);
const coverFileList = ref<UploadFileInfo[]>([]);
const galleryFileList = ref<UploadFileInfo[]>([]);

const modelForm = reactive({
  name: "",
  categoryId: undefined,
  brandId: undefined,
  sort: 0,
  slug: "",
  coverImage: {
    id: "",
    url: "",
  },
  status: undefined,
  originalPrice: 0,
  currentPrice: 0,
  tag: "",
  sku: "",
  weight: undefined,
  description: "",
  canTradein: "0",
  hasSerialNumber: "0",
  hasVariant: "0",
  canRepairable: "0",
  attributes: [] as any[],
  galleryImages: [] as any[],
});

const attributeSelectOpts = computed(() => {
  let opts = cloneDeep(attributes.value);
  opts.forEach((item) => {
    const id = get(item, "id");
    item.disabled = false;
    const isSeleted = modelForm.attributes.findIndex(
      (modelFormAttr) => modelFormAttr.attributeId === id
    );

    if (isSeleted >= 0) {
      item.disabled = true;
    }
  });

  return opts;
});

const showRemoveAttrBtn = computed(() => {
  return modelForm.attributes && modelForm.attributes.length > 1;
});

const showAddAttrBtn = computed(() => {
  return modelForm.attributes.length < attributes.value.length;
});

watch(
  () => modelForm.canTradein,
  (newVal) => {
    if (newVal === "1") {
      handleCanTradeinSelected();
    } else {
      handleCanTradeinUnSelected();
    }
  }
);

const handleUploadFinishCover = (payload: any) => {
  console.log(payload);
  const url = get(payload, "event.target.response.message") || "";
  const id = get(payload, "file.id") || "";
  if (url && id) {
    modelForm.coverImage.id = id;
    modelForm.coverImage.url = url;
  }
};

const handleUploadRemoveCover = (payload: any) => {
  console.log(payload);
  modelForm.coverImage.id = "";
  modelForm.coverImage.url = "";
};

const handleUploadFinishGallery = (payload: any) => {
  console.log(payload);
  const url = get(payload, "event.target.response.message") || "";
  const id = get(payload, "file.id") || "";
  if (url && id) {
    modelForm.galleryImages.push({
      url,
      id,
    });
  }
};

const handleUploadRemoveGallery = (payload: any) => {
  console.log(payload);
  const id = get(payload, "file.id") || "";
  if (id) {
    modelForm.galleryImages = modelForm.galleryImages.filter(
      (item) => item.id !== id
    );
  }
};

const generateNewAttribute = () => {
  return {
    uuid: uuidv4(),
    attributeId: undefined,
    attributeValueIds: [],
  };
};

const handleRemoveAttribute = (uuid: string) => {
  modelForm.attributes = modelForm.attributes.filter(
    (item) => item.uuid !== uuid
  );
};

const handleClearAttributeId = (payload: any) => {
  payload.attributeValues = [];
  payload.attributeValueIds = [];
};

const handleUpdateAttributeValue = (payload: any, option: SelectOption) => {
  payload.attributeValues = cloneDeep(option);
};

const handleAddAttribute = () => {
  modelForm.attributes.push(generateNewAttribute());
};

const handleCanTradeinSelected = () => {
  modelForm.attributes = [generateNewAttribute()];
  modelForm.hasVariant = "1";
};

const handleCanTradeinUnSelected = () => {
  modelForm.attributes = [];
  modelForm.hasVariant = "0";
};

const handleGetCategories = async () => {
  const res = await getCategories({
    page: 1,
    pageSize: 1000,
    status: "1",
  });
  categories.value = get(res, "result.records") || [];
};

const handleGetBrands = async () => {
  const res = await getBrands({
    page: 1,
    pageSize: 1000,
    status: "1",
  });
  brands.value = get(res, "result.records") || [];
};

const handleGetAllAttributes = async () => {
  const res = await getAllAttributes();
  attributes.value = get(res, "result") || [];
};

const getAttributeValues = (attrId: string) => {
  let valuesList: any[] = [];
  if (attrId) {
    attributes.value.filter((item) => {
      if (item.id === attrId) {
        valuesList = item.values;
      }
    });
  }

  return valuesList;
};

const handleSubmit = async () => {
  formRef.value?.validate(async (errors) => {
    if (errors) {
      message.error("请正确输入表单项");
      return;
    }

    if (modelForm.hasVariant === "1" && modelForm.attributes.length === 0) {
      message.error("请配置SKU属性");
      return;
    }

    const params = {
      ...modelForm,
      image: modelForm.coverImage.url,
      gallery: modelForm.galleryImages.map((item) => item.url),
    };
    await createProduct(params);
  });
};

onMounted(() => {
  handleGetCategories();
  handleGetBrands();
  handleGetAllAttributes();
});
</script>
